import React from 'react';
import { Form, Modal, InputNumber, Slider, Select, DatePicker } from 'antd';
import moment from 'moment';
import LimitedTextArea from '../../../components/LimitedTextArea';
import { FileFormItem } from './components';
import { cancelTask } from '../../../services';
import { workTimeFormat } from '../../../utils';
import { FORM_DEFAULT_LAYOUT, MODAL_DEFAULT_PARAM, MODAL_FORCE_PARAM } from '../config';
import styles from './index.less';

const { Option } = Select;
const CancelActionModal = ({ form, taskId, taskRecord, visible, setVisible, onOk }) => {
    // console.log('CancelActionModal -> taskRecord', taskRecord);
    // console.log('PauseActionModal -> taskId', taskId);
    const { getFieldDecorator, validateFields } = form;
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const [usedTimeFormat, setUsedTimeFormat] = React.useState('0天0小时0分钟');
    const [taskProgress, setTaskProgress] = React.useState(0);
    const [realEndTimeMode, setRealEndTimeMode] = React.useState('date');
    const [execute, setExecute] = React.useState(true);
    const [tipShow, setTipShow] = React.useState(false);
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            setConfirmLoading(true);
            // console.log(values);
            const {
                realEndTime,
                actualWorkDuration,
                taskProgress: progress,
                cancelType,
                operateReason,
                files = { uploadResourceFile: '' }
            } = values;
            const { uploadResourceFile = '' } = files;
            cancelTask({
                taskId,
                executeFlag: execute,
                actualStartTime: realEndTime
                    ? realEndTime.format(realEndTimeMode === 'date' ? 'YYYY-MM-DD 00:00:00' : 'YYYY-MM-DD HH:mm:ss')
                    : '',
                actualWorkDuration: actualWorkDuration * 60,
                operateReason,
                taskProgress: progress,
                cycleTaskCancelType: cancelType,
                resourceRelation: uploadResourceFile ? [uploadResourceFile] : []
            })
                .then(res => {
                    const { code } = res;
                    if (code === 10000) {
                        if (onOk) onOk();
                        setVisible(false);
                    }
                })
                .finally(() => {
                    setConfirmLoading(false);
                });
        });
    };

    const handleTimeChange = val => {
        if (Number(val)) {
            setUsedTimeFormat(workTimeFormat(val * 60));
        } else {
            setUsedTimeFormat('0天0小时0分钟');
        }
    };

    const handleSliderChange = value => {
        setTaskProgress(value);
    };

    const handleRealEndTimePanel = (value, mode) => {
        setRealEndTimeMode(mode);
    };

    const handleExecuteChange = val => {
        // console.log('CancelActionModal -> val', val);
        if (val) {
            setExecute(true);
            setTimeout(() => {
                if (taskRecord) {
                    if (taskRecord.taskProgress) {
                        setTaskProgress(taskRecord.taskProgress);
                        form.setFieldsValue({
                            taskProgress: taskRecord.taskProgress
                        });
                    }
                    if (taskRecord.actualWorkDuration) {
                        form.setFieldsValue({
                            actualWorkDuration: taskRecord.actualWorkDuration / 60
                        });
                        setUsedTimeFormat(workTimeFormat(taskRecord.actualWorkDuration));
                    }
                }
            }, 10);
            return;
        }
        setExecute(false);
    };

    const getStartTime = () => {
        if (taskRecord && taskRecord.planStartTime) {
            return moment(taskRecord.planStartTime).format(
                taskRecord.planStartTime.indexOf('00:00:00') !== -1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'
            );
        }
        return '';
    };

    const handleTypeSelect = val => {
        if (val === 2) {
            setTipShow(true);
        } else {
            setTipShow(false);
        }
    };

    React.useEffect(() => {
        if (visible) {
            setExecute(true);
            setTaskProgress(0);
            setUsedTimeFormat('0天0小时0分钟');
            setRealEndTimeMode('date');
            form.resetFields();
        }
        if (visible && taskRecord) {
            setTaskProgress(taskRecord.taskProgress);
            form.setFieldsValue({
                taskProgress: taskRecord.taskProgress
            });
            if (taskRecord.actualWorkDuration) {
                form.setFieldsValue({
                    actualWorkDuration: taskRecord.actualWorkDuration / 60
                });
                setUsedTimeFormat(workTimeFormat(taskRecord.actualWorkDuration));
            } else {
                form.setFieldsValue({
                    actualWorkDuration: ''
                });
                setUsedTimeFormat('0天0小时0分钟');
            }
            if (taskRecord.actualStartTime) {
                form.setFieldsValue({
                    realEndTime: moment(taskRecord.actualStartTime)
                });
                if (taskRecord.actualStartTime.indexOf('00:00:00') !== -1) {
                    setRealEndTimeMode('date');
                } else {
                    setRealEndTimeMode('time');
                }
            }
        }
    }, [visible, taskRecord]);

    return (
        <Modal
            {...MODAL_DEFAULT_PARAM}
            title="取消"
            width={720}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            wrapClassName={styles.miniMarginBottom}
            onCancel={() => setVisible(false)}
            {...MODAL_FORCE_PARAM}
        >
            <Form {...FORM_DEFAULT_LAYOUT} labelCol={{ span: 6 }}>
                {/* <Form.Item label="温馨提示">确定后，需由验收人/发起人通过后方可生效</Form.Item> */}
                {taskRecord.auditEmployeeName && (
                    <Form.Item label="温馨提示">
                        确定后，需由审核人【{taskRecord.auditEmployeeName}】通过后方可生效
                    </Form.Item>
                )}
                {!taskRecord.auditEmployeeName && taskRecord.launchEmployeeName && (
                    <Form.Item label="温馨提示">
                        确定后，需由发起人【{taskRecord.launchEmployeeName}】通过后方可生效
                    </Form.Item>
                )}
                <Form.Item label="是否已执行">
                    {getFieldDecorator('isExecuted', {
                        initialValue: 1,
                        rules: [
                            {
                                required: true,
                                message: '请选择是否已执行！'
                            }
                        ]
                    })(
                        <Select style={{ width: 200 }} placeholder="请选择是否已执行" onChange={handleExecuteChange}>
                            <Option value={1}>是</Option>
                            <Option value={0}>否</Option>
                        </Select>
                    )}
                </Form.Item>
                {execute && (
                    <>
                        <Form.Item label="开始时间" className={styles.disabledItem}>
                            {getStartTime()}
                        </Form.Item>
                        <Form.Item label="实际开始时间">
                            {getFieldDecorator('realEndTime', {
                                initialValue:
                                    taskRecord && taskRecord.actualStartTime
                                        ? moment(taskRecord.actualStartTime)
                                        : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择实际开始时间！'
                                    }
                                ]
                            })(
                                <DatePicker
                                    showTime
                                    style={{ width: 300 }}
                                    placeholder="请选择实际开始时间"
                                    format={realEndTimeMode === 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'}
                                    onPanelChange={handleRealEndTimePanel}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="已用工时">
                            {getFieldDecorator('actualWorkDuration', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入已用工时！'
                                    }
                                ]
                            })(
                                <InputNumber
                                    min={0}
                                    max={9999.9}
                                    precision={1}
                                    placeholder="请输入已用工时"
                                    formatter={value => `${value}`.replace('.0', '')}
                                    style={{ width: 150, marginRight: 10 }}
                                    onChange={handleTimeChange}
                                />
                            )}
                            小时（{usedTimeFormat}）
                        </Form.Item>
                        <Form.Item label="当前进度">
                            <span
                                style={{
                                    position: 'absolute',
                                    display: 'block',
                                    width: 50,
                                    left: 320,
                                    color: '#585858'
                                }}
                            >
                                {taskProgress}%
                            </span>
                            {getFieldDecorator('taskProgress', {
                                initialValue: 0
                            })(<Slider onChange={handleSliderChange} style={{ width: 300 }} />)}
                        </Form.Item>
                    </>
                )}
                {taskRecord && taskRecord.cycleTaskFlag && (
                    <Form.Item label="周期任务取消类型">
                        {getFieldDecorator('cancelType', {
                            initialValue: 1
                        })(
                            <Select style={{ width: 200 }} placeholder="请选择取消类型" onSelect={handleTypeSelect}>
                                <Option value={1}>取消当前任务</Option>
                                <Option value={2}>取消所有任务</Option>
                            </Select>
                        )}
                        {tipShow && <span>（已执行工时仅记录至当前任务）</span>}
                    </Form.Item>
                )}
                <Form.Item label="原因说明">
                    {getFieldDecorator('operateReason', {
                        rules: [
                            {
                                required: true,
                                message: '请输入原因'
                            }
                        ]
                    })(<LimitedTextArea placeholder="请输入原因" />)}
                </Form.Item>
                <FileFormItem form={form} />
            </Form>
        </Modal>
    );
};

export default Form.create()(CancelActionModal);
